package com.yaowk.common.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by yaowk on 17-8-15.
 */
public class CorsInterceptor implements Interceptor {
    protected String origin = "";
    protected String methods = "GET,POST,PUT,OPTIONS";
    protected boolean credentials = true;

    public CorsInterceptor(String origin, String methods, boolean credentials) {
        this.origin = origin;
        this.methods = methods;
        this.credentials = credentials;
    }

    public CorsInterceptor() {
    }

    @Override
    public void intercept(Invocation invocation) {
        HttpServletResponse response = invocation.getController().getResponse();
        if (StrKit.notBlank(origin)) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        } else {
            response.setHeader("Access-Control-Allow-Origin", invocation.getController().getHeader("Origin"));
        }
        response.setHeader("Access-Control-Allow-Methods", methods);
        if (credentials)
            response.setHeader("Access-Control-Allow-Credentials", "true");
        invocation.invoke();
    }
}
